package com.treasure.service.creditCard.service.impl;

import com.treasure.service.commons.lang.util.IdCreater;
import com.treasure.service.commons.lang.util.MD5Util;
import com.treasure.service.config.MQProperties;
import com.treasure.service.creditCard.service.CreditCardService;
import com.treasure.service.domain.TBankConfig;
import com.treasure.service.dto.bank91.*;
import com.treasure.service.dto.ApplyForDto;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.mapper.TBankConfigMapper;
import com.treasure.service.third.utils.RestClient;
import com.treasure.service.rabbit.service.SendMqService;
import com.treasure.service.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
* @Description:    办理信用卡等业务
* @Author:         panxinwen
* @CreateDate:     2018/12/1 0:23
* @Version:        1.0
*/
@Service
public class CreditCardServiceImpl implements CreditCardService {

    @Autowired
    private SendMqService sendMqService;

    @Autowired
    private MQProperties mqProperties;

    @Autowired
    RestClient restClient;

    @Value("${creditCard.applyFor.w91}")
    private String applyFor91;

    @Value("${creditCard.applyFor.w91}")
    private String getBank91;

    @Value("${creditCard.w91.token}")
    private String token;

    @Value("${creditCard.w91.getapplyState}")
    private String getapplyState;

    @Autowired
    private TBankConfigMapper tBankConfigMapper;

    @Override
    public ResponseResult queryCreditCardSchedule(ApplyForDto applyForDto) {
//        CreditApplyFor91Dto applyFor91Dto = new CreditApplyFor91Dto();
//        applyFor91Dto.setName(applyForDto.getApply_name());
//        applyFor91Dto.setIdcard(applyForDto.getApply_idnum());
//        applyFor91Dto.setTel(applyForDto.getApply_phone());
//        applyFor91Dto.setBankid(applyForDto.getBankCode());
//        applyFor91Dto.setToken(token);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("token",token);
        paramMap.put("bankid",applyForDto.getBankCode());
        paramMap.put("name",applyForDto.getApply_name());
        paramMap.put("idcard",applyForDto.getApply_idnum());
        paramMap.put("tel",applyForDto.getApply_phone());

        //调用三方API查询信用卡办理进度
        CreditGetapplyStateResult91 result = restClient.post(getapplyState,paramMap,CreditGetapplyStateResult91.class);

        if (result.isSuccess()){
            sendMqService.sendMsgServiceJson(mqProperties.getCardDisposeResultKey(),result.getData());
            return new ResponseResult(CodeEnum.SUCCESS,result.getData());
        }

        return new ResponseResult(CodeEnum.FAIL);

    }

    @Override
    public ResponseResult applyFor(ApplyForDto applyForDto) {
        String type = applyForDto.getChannel();
        if (true){

//            CreditApplyFor91Dto applyFor91Dto = new CreditApplyFor91Dto();
//            applyFor91Dto.setName(applyForDto.getApply_name());
//            applyFor91Dto.setIdcard(applyForDto.getApply_idnum());
//            applyFor91Dto.setTel(applyForDto.getApply_phone());
//            applyFor91Dto.setBankid(applyForDto.getBankCode());
//            applyFor91Dto.setToken(token);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("token",token);
            paramMap.put("bankid",applyForDto.getBankCode());
            paramMap.put("name",applyForDto.getApply_name());
            paramMap.put("idcard",applyForDto.getApply_idnum());
            paramMap.put("tel",applyForDto.getApply_phone());

            CreditApplyResult91 result = restClient.post(applyFor91,paramMap,CreditApplyResult91.class);

            if (result.isSuccess()){

                return new ResponseResult(CodeEnum.SUCCESS,result.getData());

            }

            return new ResponseResult(CodeEnum.CREDITCARD_FAIL);
        }else {
            String url = applyForhx(applyForDto);
            return new ResponseResult(CodeEnum.SUCCESS,url);
        }

    }


    public String applyForhx(ApplyForDto applyForDto) {
        String url="http://180.167.88.130:38080/xinbox/toApplyCredit_inst";
        TreeMap<String, String> map = new TreeMap<String, String>();
        map.put("apply_name",applyForDto.getApply_name()+"&");
        map.put("apply_idnum",applyForDto.getApply_idnum()+"&");
        map.put("apply_phone",applyForDto.getApply_phone()+"&");
        map.put("apply_type","1&");
        map.put("areaCode","510100&");
        map.put("orgno","88888&");
        map.put("operCode","12345&");
        map.put("platform","66");

        System.out.println("待加密的参数==="+getParameters(map)+"&key=Qwer123");
        System.out.println("加密后的参数==="+MD5Util.MD5(getParameters(map)+"&key=Qwer123"));
//        map.put("sign",MD5Util.MD5(getParameters(map).toUpperCase()));

        String sign =MD5Util.MD5(getParameters(map)+"&key=Qwer123").toUpperCase();

        map.remove("apply_name");
        try {
            map.put("apply_name",URLEncoder.encode(applyForDto.getApply_name(), "UTF-8")+"&");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url=url+"?"+getParameters(map)+"&sign="+sign;
        System.out.println("网申地址===="+url);

        return url;

    }

    @Override
    public GetBankResult91 getBank() {

        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        GetBankResult91 getBankResult91 =restClient.get(getBank91,map,GetBankResult91.class);

        getBankResult91.getData().forEach(getBankData91 ->{

            TBankConfig tBankConfig = new TBankConfig();
            tBankConfig.setBankId(getBankData91.getId());
            tBankConfig = tBankConfigMapper.selectOne(tBankConfig);

            if (tBankConfig == null || tBankConfig.getId() == null){

                tBankConfig = new TBankConfig();
                tBankConfig.setId(IdCreater.getLongId());
                tBankConfig.setBankUrl(getBankData91.getUrl());
                tBankConfig.setBankId(getBankData91.getId());
                tBankConfig.setLogoUrl(getBankData91.getLogo());

                tBankConfigMapper.insert(tBankConfig);

            }else {
                tBankConfig.setBankUrl(getBankData91.getUrl());
                tBankConfigMapper.updateByPrimaryKeySelective(tBankConfig);
            }


        });

        return getBankResult91;
    }

    public String getParameters(TreeMap<String, String> map){
        String prepayid = "";
        Set es=map.entrySet();
        Iterator it=es.iterator();
        StringBuffer sb = new StringBuffer("");
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            sb.append(k+"=");
            String v = (String) entry.getValue();
            sb.append(v);
        }
        String params=sb.substring(0);

        return params;
    }

}
